// 音效管理工具
class AudioManager {
  constructor() {
    this.sounds = {}
    this.music = null
    this.isMuted = false
    this.volume = 0.3
    this.musicVolume = 0.2
  }

  // 初始化音效
  init() {
    this.loadSounds()
    this.loadMusic()
  }

  // 加载音效文件
  loadSounds() {
    const soundFiles = {
      click: '/sounds/click.mp3',
      paperOpen: '/sounds/paper-open.mp3',
      success: '/sounds/success.mp3',
      heartbeat: '/sounds/heartbeat.mp3'
    }

    Object.entries(soundFiles).forEach(([name, path]) => {
      this.sounds[name] = new Audio(path)
      this.sounds[name].preload = 'auto'
      this.sounds[name].volume = this.volume
    })
  }

  // 加载背景音乐
  loadMusic() {
    this.music = new Audio('/music/romantic-background.mp3')
    this.music.loop = true
    this.music.preload = 'auto'
    this.music.volume = this.musicVolume
  }

  // 播放音效
  async playSound(soundName) {
    if (this.isMuted || !this.sounds[soundName]) return

    try {
      this.sounds[soundName].currentTime = 0
      await this.sounds[soundName].play()
    } catch (error) {
      console.log(`音效播放失败: ${soundName}`, error)
    }
  }

  // 播放背景音乐
  async playMusic() {
    if (this.isMuted || !this.music) return

    try {
      await this.music.play()
    } catch (error) {
      console.log('背景音乐播放失败:', error)
    }
  }

  // 停止背景音乐
  stopMusic() {
    if (this.music) {
      this.music.pause()
      this.music.currentTime = 0
    }
  }

  // 暂停背景音乐
  pauseMusic() {
    if (this.music) {
      this.music.pause()
    }
  }

  // 恢复背景音乐
  resumeMusic() {
    if (this.music && !this.isMuted) {
      this.music.play()
    }
  }

  // 设置音量
  setVolume(volume) {
    this.volume = Math.max(0, Math.min(1, volume))
    Object.values(this.sounds).forEach(sound => {
      sound.volume = this.volume
    })
  }

  // 设置音乐音量
  setMusicVolume(volume) {
    this.musicVolume = Math.max(0, Math.min(1, volume))
    if (this.music) {
      this.music.volume = this.musicVolume
    }
  }

  // 静音/取消静音
  toggleMute() {
    this.isMuted = !this.isMuted
    if (this.isMuted) {
      this.pauseMusic()
    } else {
      this.resumeMusic()
    }
    return this.isMuted
  }

  // 播放信封打开序列
  async playEnvelopeSequence() {
    // 点击音效
    await this.playSound('click')
    
    // 延迟播放打开音效
    setTimeout(() => {
      this.playSound('paperOpen')
    }, 200)
    
    // 延迟播放成功音效
    setTimeout(() => {
      this.playSound('success')
    }, 1000)
    
    // 延迟播放心跳音效
    setTimeout(() => {
      this.playSound('heartbeat')
    }, 2000)
  }

  // 播放浪漫音效序列
  async playRomanticSequence() {
    await this.playSound('success')
    setTimeout(() => {
      this.playSound('heartbeat')
    }, 500)
  }

  // 清理资源
  destroy() {
    Object.values(this.sounds).forEach(sound => {
      sound.pause()
      sound.src = ''
    })
    if (this.music) {
      this.music.pause()
      this.music.src = ''
    }
  }
}

// 创建全局音效管理器实例
const audioManager = new AudioManager()

export default audioManager
